<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>固定侧边栏</title>
    <style>
        div {
            width: 1200px;
            height: 600px;
            background-color: pink;
            margin-bottom: 10px;
            float: left;
        }

        .header {
            height: 200px;
        }

        .slider-ber {
            position: absolute;
            top: 50%;
            left: 50%;
            margin-left: 560px;
            width: 30px;
            height: 100px;
            background-color: blue;
            float: right;
        }

        .goBack {
            display: none;
        }
    </style>
</head>

<body>
    <div class="slider-ber">
        <span class="goBack">返回顶部</span>
    </div>
    <div class="header">头部区域</div>
    <div class="banner">banner区域</div>
    <div class="main">主体部分</div>
    <script>
        var sliderber = document.querySelector('.slider-ber')
        var banner = document.querySelector('.banner')
        var bannerTop = banner.offsetTop ;
        var sliderberTop = sliderber.offsetTop - bannerTop;
        var main = document.querySelector('.main')
        var goBack = document.querySelector('.goBack')
        var mainTop = main.offsetTop - 800;
        // 页面滚动事件 scroll
        document.addEventListener('scroll', function () {
            // window.pageYOffset 被卷去的头部距离
            if (window.pageYOffset >= bannerTop) {
                // 但被卷去头部距离大于等于170时 侧边栏改为固定定位
                sliderber.style.position = 'fixed';
                sliderber.style.top = sliderberTop + 'px';
            }
            else {
                // 其余为相对定位
                sliderber.style.position = 'absolute';
                sliderber.style.top = '50%'
            }
            if (window.pageYOffset >= mainTop) {
                goBack.style.display = 'block'
                
            }
            else {
                goBack.style.display = 'none'
            }
        })
    </script>
</body>

</html>